package com.wq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.wq.common.CustomerException;
import com.wq.common.R;
import com.wq.dto.SetmealDto;
import com.wq.entity.Category;
import com.wq.entity.Setmeal;
import com.wq.entity.SetmealDish;
import com.wq.service.CategoryService;
import com.wq.service.SetmealDishService;
import com.wq.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-23 11:39
 */
@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    SetmealService setmealService;

    @Autowired
    SetmealDishService setmealDishService;

    @Autowired
    CategoryService categoryService;

    /**
     * 保存套餐，保存套餐关联的菜品信息
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithDishes(setmealDto);
        return R.success("添加套餐成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        /**
         * 根据 page 和 pageSize ，name 查询封装好 setmealPage 对象
         */
        Page<Setmeal> pageInfoForSetmeal = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Setmeal::getName, name);
        Page<Setmeal> setmealPage = setmealService.page(pageInfoForSetmeal, lqw);

        /**
         * 因为前台需要 categoryName 字段，所以需要封装 setmealDtoPage 返回给前台
         */
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        List<Setmeal> setmealRecords = setmealPage.getRecords();
        List<SetmealDto> setmealDtoRecords = setmealRecords.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            final Long categoryId = item.getCategoryId();
            final Category category = categoryService.getById(categoryId);
            final String categoryName = category.getName();
            setmealDto.setCategoryName(categoryName);
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealDtoRecords);
        return R.success(setmealDtoPage);
    }

    /**
     * 删除 Setmeal 表中套餐数据的同时，要删除 SetmealDish 表中套餐内菜品的数据
     * "@RequestBody - json / @RequestParam - 数组-> 列表 自动转换/ @PathVariable - restful风格"
     * "数组->List : Arrays.asList()"
     * "List->数组 : list.toArray()"
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    /**
     * 执行delete方法后将缓存中setmealCache中所有的缓存数据清空
     */
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        /**
         * 套餐在售时不能删除
         * select count(*) from setmeal where id in (ids) and status = 0
         */
        LambdaQueryWrapper<Setmeal> lqwForSetmeal = new LambdaQueryWrapper<>();
        lqwForSetmeal.in(Setmeal::getId, ids);
        lqwForSetmeal.eq(Setmeal::getStatus, 0);
        final int count = setmealService.count(lqwForSetmeal);
        if (count > 0) {
            throw new CustomerException("套餐在售时不能删除!");
        }
        /**
         * delete from setmeal where id in ids
         */
        setmealService.removeByIds(ids);
        /**
         * delete from setmeal_dish where setmeal_id in (ids)
         */
        LambdaQueryWrapper<SetmealDish> lqwForSetmealDish = new LambdaQueryWrapper<>();
        lqwForSetmealDish.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lqwForSetmealDish);
        return R.success("删除套餐成功!");
    }

    @GetMapping("/list")
    /**
     * 加入缓存的对象需要实现序列化接口
     */
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByAsc(Setmeal::getUpdateTime);
        final List<Setmeal> setmealList = setmealService.list(lqw);
        return R.success(setmealList);
    }
}
